# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name： distance
Description :
Author : 'li'
date： 2022/2/22
-------------------------------------------------
Change Activity:
2022/2/22:
-------------------------------------------------
"""
import numpy as np
import cv2
from .bbox_transform import single_xyxy2poly


def get_distance(p1, p2):
    """
    Calculate distance between two points.

    Args:
        p1:
        p2:

    Returns:

    """
    return np.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)


def get_distance_point_to_contours(p, contour, is_abs=True):
    """
    pointPolygonTest

    Args:
        p:
        contour:
        is_abs:

    Returns:

    """
    tmp_p = p.astype(np.int32)
    tmp_contour = contour.astype(np.int32)
    distance = cv2.pointPolygonTest(tmp_contour, tmp_p.tolist(), measureDist=True)
    if is_abs:
        return abs(distance)
    return distance


def get_distance_contour_to_contour(c1, c2):
    """
    Distance between two contours.

    Args:
        c1:
        c2:

    Returns:

    """
    if len(c1.shape) == 1 and c1.shape[0] == 4:
        tmp_c1 = single_xyxy2poly(c1)
    else:
        tmp_c1 = c1.copy()
    if len(c2.shape) == 1 and c2.shape[0] == 4:
        tmp_c2 = single_xyxy2poly(c2)
    else:
        tmp_c2 = c2.copy()
    tmp_c1 = tmp_c1.reshape(-1, 2)
    tmp_c2 = tmp_c2.reshape(-1, 2)
    min_distance = 100000
    for p in tmp_c1:
        tmp_distance = get_distance_point_to_contours(p, tmp_c2)
        if tmp_distance < min_distance:
            min_distance = tmp_distance
    for p in tmp_c2:
        tmp_distance = get_distance_point_to_contours(p, tmp_c1)
        if tmp_distance < min_distance:
            min_distance = tmp_distance
    return min_distance
